package com.tjnu.baiyi.action;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.tjnu.baiyi.entity.TbMessage;
import com.tjnu.baiyi.entity.TbUser;

@Scope("prototype")
@Controller("messageAction")
public class MessageAction extends BaseAction {
	private static final long serialVersionUID = 2157846675286206383L;

	/**
	 * 添加留言
	 * 
	 * @return
	 * @throws Exception
	 */
	public String addMessage() throws Exception {
		try {
			if (message != null) {
				String id = request.getParameter("id").toString();// 获取留言接收者的id
				TbUser user1 = tbUserDao.findById(Integer.parseInt(id));
				TbUser currUser = (TbUser) session.getAttribute("currentUser");
				TbMessage tm = new TbMessage();
				tm.setMessage(message.getMessage());
				tm.setTbUserByReceiptMessageId(user1);
				tm.setTbUserBySendMessageId(currUser);
				tm.setMessageTime(getCurrentTime());
				tbMessageDao.save(tm);
			} else {
				return ERROR;
			}
			return SUCCESS;
		} catch (Exception e) {
			return ERROR;
		}
	}

	// 获取当前时间（工具）
	public Timestamp getCurrentTime() {
		// 使用默认时区和语言环境获得一个日历
		Calendar calender = Calendar.getInstance();
		// 将Calendar类型转换成Date类型
		Date tasktime = (Date) calender.getTime();
		// 设置日期输出的格式
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Timestamp time = Timestamp.valueOf(df.format(tasktime));
		return time;
	}
}
